package com.ship.contract.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.ship.common.core.enums.MessageTypeEnum;
import com.ship.common.core.enums.ModuleUrlEnum;
import com.ship.common.core.exception.BusException;
import com.ship.common.core.utils.DateUtil;
import com.ship.common.core.utils.DateUtils;
import com.ship.common.core.web.domain.BaseResultCode;
import com.ship.common.security.utils.SecurityUtils;
import com.ship.contract.bean.*;
import com.ship.contract.bean.vo.ConShippingVo;
import com.ship.contract.mapper.ConBrokerMapper;
import com.ship.contract.service.*;
import com.ship.contract.utils.FileUtil;
import com.ship.contract.utils.ObjectUtils;
import com.ship.contract.utils.PingYinUtil;
import com.ship.system.api.BpmInstanceService;
import com.ship.system.api.RemoteMessageSendService;
import com.ship.system.api.domain.SysMessageSend;
import com.ship.system.api.model.ProcessInstanceParam;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.*;

@Service("ConBrokerService")
public class ConBrokerServiceImpl extends ContractBaseServiceImpl<ConBrokerMapper, ConBroker> implements ConBrokerService {
    @Autowired
    private ConBrokerMapper conBrokerMapper;

    @Autowired
    private ConFilesService conFilesService;

    @Autowired
    private ConOperateService conOperateService;

    @Autowired
    private ConExcellentCasesService conExcellentCasesService;

    @Autowired
    private ConAllLabelService conAllLabelService;

    @Resource
    private RemoteMessageSendService remoteMessageSendService;

    @Autowired
    private ConShippingService conShippingService;

    @Value("${file.http-domain}")
    private String httpUrl;
    @Value("${file.https-domain}")
    private String httpsUrl;

    @Override
    public List<ConShippingVo> getConShippingNames(String name) {
        return conShippingService.getConShippingNames(name);
    }

    @Override
    public void saveCon(ConBroker conBroker) {
        conBroker.setStatus(1);
        conBroker.setDelApply(0);
        conBroker.setExcellent(0);

        conBroker.setContractName(editContractName(conBroker));
        conBroker.setContractNumber(editContractNumbers(conBroker));

        super.save(conBroker);
        ConFiles conFile = new ConFiles();
        conFile.setConId(conBroker.getId());
        conFile.setFileType(1);
        String path = conBroker.getFilePath();
        conFile.setUrl(path);
        conFile.setNewUrl(path);
        conFile.setFileName(path.substring(path.lastIndexOf("/") + 1, path.length()));
        conFile.setScanPdf(FileUtil.getIsScanPdf(path));
        //保存附件
        conFilesService.save(conFile);
        conOperateService.saveByCon("新增合同", conBroker.getId());

    }

    @Override
    public void updateCon(ConBroker conBroker) {
        ConBroker OldConBroker = conBrokerMapper.getById(conBroker.getId());

        String oldContractNumber = incrementLastDigit(OldConBroker.getContractNumber());
        conBroker.setContractName(editContractName(conBroker));

        String newContractNumbers = editContractNumbers(conBroker);
        if (newContractNumbers.equals(oldContractNumber)) {
            conBroker.setContractNumber(OldConBroker.getContractNumber());
        } else {
            conBroker.setContractNumber(newContractNumbers);
        }
        super.updateById(conBroker);

        if (StringUtils.isNotBlank(conBroker.getTcpRelateId())) {
            String[] conShipId = conBroker.getTcpRelateId().split(",");
            if (null != conShipId && conShipId.length > 0) {
                for (String id : conShipId) {
                    ConShipping conShipping = conShippingService.getById(id);
                    if (null != conShipping) {
                        String shipBroker = conBroker.getPartnerB();
                        conShipping.setShipBroker(shipBroker);
                        conShippingService.updateById(conShipping);
                    }
                }
            }
        }

        ConExcellentCases conExcellentCases = conExcellentCasesService.getAllByConId(conBroker.getId());
        if (conExcellentCases != null) {
            conExcellentCases.setContractName(conBroker.getContractName());
            conExcellentCases.setContractNumber(conBroker.getContractNumber());
            conExcellentCasesService.updateById(conExcellentCases);
        }

        conOperateService.saveByCon("修改合同", conBroker.getId());
    }

    //拼接合同名字
    @Override
    public String editContractName(ConBroker conBroker) {
        String str1 = conBroker.getPartnerB();
        Date signingDate = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy.MM.dd");
        String str5 = sdf.format(signingDate);
        String contractName = "BA-" + str1 + "-" + str5;
        return contractName;
    }

    @Override
    public String editContractNumbers(ConBroker conBroker) {
        // 获取所有合同编号
        List<String> strings = conBrokerMapper.getAllContractNumbers(conBroker.getPartnerB());
        String name = conBroker.getPartnerB();
        String str1 = checkChineseAndEnglish(name);
        int maxNumber = extractAndFindMaxNumberd(strings, str1);
        String ContractNum = "BA-" + str1 + "-" + maxNumber;
        return ContractNum;
    }

    @Override
    public void delApply(Long id) {
        ConBroker conBroker = super.getById(id);
        if (conBroker == null) {
            throw new BusException("删除申请失败!,该合同不存在", BaseResultCode.GENERAL_ERROR);
        }
        if (conBroker.getDelApply() == 1) {
            throw new BusException("当前合同已发起删除申请，请勿重复提交", BaseResultCode.GENERAL_ERROR);
        }
        conBroker.setDelApply(1);
        //启动删除审批流程
        ProcessInstanceParam param = new ProcessInstanceParam();
        param.setBussinessId(id);
        param.setBpmKey(BpmInstanceService.SYSTEM_DELETE_BPM_KEY);
        Map<String, Object> map = new HashMap<>();
        map.put("serviceType", 10);
        map.put("module", "con");
        map.put("moduleName","船舶经纪人合同");
        map.put("reason","");
        param.setParams(map);
        String processInstanceId = bpmInstanceService.startProcessInstance(param);
        conBroker.setDeleteProcessInstanceId(processInstanceId);
        //conBroker.setDelApply(true);
        super.updateById(conBroker);
    }

    @Override
    public Map<String, Object> detail(Long id) {
        Map<String, Object> result = new HashMap<>();
        result.put("data", super.getById(id));
        result.put("optRecord", conOperateService.listByConId(id));
        result.put("contractLabels", conAllLabelService.listByConId(id));
//        result.put("files", conFilesService.listByConId(id));
        List<ConFiles> conFiles = conFilesService.listByConId(id);
        if(conFiles!=null && conFiles.size()>0){
            conFiles.stream().forEach(c->{
                c.setUrl(c.getUrl().replace(httpUrl, httpsUrl));
                c.setNewUrl(c.getUrl());
            });
        }
        result.put("files",conFiles);
        return result;
    }

    @Resource
    BpmInstanceService bpmInstanceService;

    @Override
    public void excellent(ConExcellentCases conExcellentCases, String currentUserName) {
        ConBroker conBroker = super.getById(conExcellentCases.getId());
        if (conBroker == null) {
            throw new BusException("申请失败!,该合同不存在", BaseResultCode.GENERAL_ERROR);
        }
        ConExcellentCases existByConId = conExcellentCasesService.getAllByConId(conExcellentCases.getId());
        if (existByConId != null) {
            throw new BusException("该合同已经存在优秀案例", BaseResultCode.GENERAL_ERROR);
        }
        conExcellentCases.setId(null);
        conExcellentCases.setContractName(conBroker.getContractName());
        conExcellentCases.setContractNumber(conBroker.getContractNumber());
        conExcellentCases.setConId(conBroker.getId());
        conExcellentCases.setTypeOfContract(10);
        conExcellentCases.setApplicant(currentUserName);
        conExcellentCases.setCreateBy(SecurityUtils.getUsername());

        //启动审批流程
        ProcessInstanceParam param = new ProcessInstanceParam();
        param.setBussinessId(conBroker.getId());
        param.setBpmKey(BpmInstanceService.CON_RESOURCE_BOM_KEY);
        Map<String, Object> map = new HashMap<>();
        try {
            map = ObjectUtils.objectToMap(conExcellentCases);
        } catch (IllegalAccessException e) {
            throw new RuntimeException(e);
        }
        map.put("moduleName","船舶经纪人合同");
        map.put("reason",conExcellentCases.getExcellent());
        map.put("serviceType", 10);
        param.setParams(map);
        String processInstanceId = bpmInstanceService.startProcessInstance(param);
        conExcellentCases.setProcessInstanceId(processInstanceId);
        conExcellentCasesService.save(conExcellentCases);
        conBroker.setExcellent(1);
        super.updateById(conBroker);
    }

    //获取首字母大写
    public static String checkChineseAndEnglish(String str) {
        boolean isEnglishWord = str.matches("[a-zA-Z0-9]+"); // 检查是否是英文单词（包括数字）

        if (isEnglishWord) {
            boolean containsSeparator = str.trim().matches(".*[\\s\\p{Punct}]+.*"); // 检查字符串中是否包含空格或其他分隔符

            if (!containsSeparator) {
                // 如果字符串中没有分隔符，则直接返回原字符串
                return str;
            }
        }

        boolean newWord = true; // 用于标记是否是一个新单词的开头
        StringBuilder result = new StringBuilder();
        for (char c : str.toCharArray()) {
            if (Character.toString(c).matches("[\\u4E00-\\u9FA5]+")) {
                String pinyin = PingYinUtil.getPinYinHeadChar(Character.toString(c));
                result.append(pinyin.toUpperCase());
            } else if (Character.isLetter(c)) {
                if (newWord) {
                    char firstLetter = Character.toUpperCase(c);
                    result.append(firstLetter);
                    newWord = false;
                }
            } else if (Character.isDigit(c)) {
                result.append(c);
            } else {
                newWord = true; // 遇到非字母字符，标记为新单词的开头
            }
        }
        return result.toString();
    }

    public int extractAndFindMaxNumberd(List<String> strings, String keyword) {
        int maxNumber = 0; // 初始化为 0
        for (String str : strings) {
            // 使用正则表达式提取数字部分
            String numberPart = str.substring(str.lastIndexOf('-') + 1);
            try {
                int number = Integer.parseInt(numberPart);
                maxNumber = Math.max(maxNumber, number);
            } catch (NumberFormatException e) {
                // 如果无法解析数字，忽略当前字符串
            }
        }
        return maxNumber + 1;
    }

    @Override
    public void contractExpireMessageSend() {
        List<ConBroker> contractList = this.baseMapper.selectList(
                new LambdaQueryWrapper<ConBroker>()
                        .ge(ConBroker::getExpirationDate, new Date())
        );
        if (contractList.size() == 0) {
            return;
        }
        List<SysMessageSend> messageSendList = new LinkedList<>();
        for (ConBroker contractInfo : contractList) {
            SysMessageSend messageSend = new SysMessageSend();
            messageSend.setMessageUrl(ModuleUrlEnum.CBJJRHTXQ.getUrl() + contractInfo.getId());
            messageSend.setMessageType(MessageTypeEnum.MESSAGE_TYPE_8.getCode());
            messageSend.setContentParam(new String[]{contractInfo.getContractName()
                    , contractInfo.getContractNumber()
                    , DateUtils.parseDateToStr("yyyy-MM-dd", contractInfo.getExpirationDate())});
            messageSend.setCompareType(5);
            messageSend.setCompareValue(DateUtil.getDateDays(new Date(), contractInfo.getExpirationDate(), 1).intValue());
            messageSendList.add(messageSend);
        }
        remoteMessageSendService.messageSendBatch(messageSendList);
    }
}
